package mission_tour.solution;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;

public class background_event_service extends Service implements Runnable,LocationListener,ServerIp{
	private int tServiceid;		//시작 아이디
	private Handler tHandler;	//서비스에 연결된 핸들러 타이머 이용한 반복 처리시 사용
	private boolean tRunning;	//서비스 동작 여부 flag
	
	private static int Counter = 10;	//최대 실행할 갯수
	private int tCounter;
	
	LocationManager lm = null;
	MediaPlayer mp;
	
	public void onCreate(){
		super.onCreate();
		tHandler = new Handler();
		tRunning = false;
	}
	
	public void onStart(Intent intent,int startid){		//클래스 실행시 동시 실행
		super.onStart(intent,startid);
		tServiceid = startid;
		tCounter = Counter;
		
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.NO_REQUIREMENT);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        String best = lm.getBestProvider(criteria, true);
        lm.requestLocationUpdates(best, 10000, 0, this);
        
        if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        	if(!tRunning){
    			tHandler.postDelayed(this, items.TIMER_RELOAD);	//일정 시간마다 메소드 호출
    			tRunning = true;
    		}
        }
	}
	
	public void onDestroy(){
		tRunning = false;
		super.onDestroy();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(!tRunning){	//서비스 종료 요청이 들어오면 종료
			return;
//		}else if(--tCounter <= 0){	//지정한 횟수 실행이면 스스로 종료
//			stopSelf(tServiceid);
		}else{	//다음 작업을 요구
			try {
				for (int idx = 0; idx < items.event_position_list.size(); idx++) {
					if((items.my_positionX >= items.event_position_list.get(idx).getEvent_startX()) && (items.my_positionX <= items.event_position_list.get(idx).getEvent_endX())&&((items.my_positionY >= items.event_position_list.get(idx).getEvent_startY())&&(items.my_positionY <= items.event_position_list.get(idx).getEvent_endY()))){
						items.event_position = items.event_position_list.get(idx).getEvent_position_no();
						//items.event_position = items.event_position_list.get(0).getEvent_position_no();
						if(!items.event_called){							
							URL url = null;
					        
				        	url = new URL(event_check+"?event_position="+items.event_position+"&c_code="+items.c_code+"&app_type="+items.apptype);
				        	
					        HttpURLConnection http = (HttpURLConnection)url.openConnection();
					
							BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
							StringBuffer buffer = new StringBuffer();
							 
							int z;
							
							while((z=in.read()) != -1){
								buffer.append((char)z);
							}
							
							String[] result = buffer.toString().trim().split(",");
							
							if(result[0].equals("1")){
								items.event_type = Integer.parseInt(result[1].trim());	//해당 위치 이벤트 타입 변수
								items.event_name = result[2].trim();					//해당 위치 이벤트 이름 변수
								
					            mp = MediaPlayer.create(this, R.raw.dingdong);	//알람 울림
					            mp.start();
					             
								Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);	//진동울림
								vibrator.vibrate(2500);		//진동울리는 시간
															
								Intent popupIntent = new Intent(this, service_dialog_call.class);	//팝업창 띄우기
								PendingIntent pi = PendingIntent.getActivity(this, 0, popupIntent, PendingIntent.FLAG_ONE_SHOT);
								
								pi.send();
							}
							break;
						}
					}
				}
				items.TIMER_RELOAD = 15000;
				tHandler.postDelayed(this, items.TIMER_RELOAD);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch(Exception e){
				System.out.println(e.toString());
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		items.my_positionX = location.getLatitude();
		items.my_positionY = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
